<!-- 聊天窗口 -->
<template>
  <div id="chatWindowContainer"
       class="chat-window-container">
    <!-- <van-pull-refresh v-model="isLoading"
                      success-text="刷新成功"> -->
    <div class="chat-content"
         :style="'height:'+ chatContentHeight">
      <!-- recordContent 聊天记录数组-->
      <div v-for="(item, index) in chatRecords"
           :key="index">
        <!-- 对方 -->
        <div class="word"
             v-if="!item.fromMe">
          <img :src="item.avatarUrl"
               @click="navigatorOthersInfo(item.userId)" />

          <div class="info">
            <p class="time">{{ item.nickName }} {{$filters.dataformat(Number(item.sendMsgTime), "YYYY-MM-DD HH:mm:ss")}}</p>
            <div class="content-more-style">

              <div class="info-content">
                <!-- 文本 -->
                <div v-if="item.chatContentType===0"
                     class="chat-margin"><span v-html="item.chatContent"></span></div>

                <div v-else-if="item.chatContentType===2"
                     v-for="(file,index1) in item.chatContent"
                     :key="index1">
                  <!-- 图片 -->
                  <template v-for="(tupian, i0) in $fileSuffix.tupian"
                            :key="i0">
                    <chat-image v-if="tupian === file.fileSuffix"
                                :imgSrc="file.fileUrl"></chat-image>
                  </template>

                  <!-- 语音 -->
                  <chat-yuyin v-if="file.fileSuffix === '.wav' && file.isYuyin === 1"
                              :yuyinSrc="file.fileUrl"
                              :fromMe="item.fromMe"></chat-yuyin>

                  <!-- 视频 -->
                  <template v-for="(shipin, i1) in $fileSuffix.shipin"
                            :key="i1">
                    <video-player v-if="shipin.suffix === file.fileSuffix"
                                  class="vjs-custom-skin"
                                  ref="videoPlayer"
                                  :playsinline="true"
                                  :options="{...playerOptions, sources: [{type: shipin.mime, src: file.fileUrl }]}"></video-player>
                  </template>

                  <!-- 音频 -->
                  <template v-for="(yinpin, i2) in $fileSuffix.yinpin"
                            :key="i2">
                    <aplayer v-if="yinpin === file.fileSuffix  && file.isYuyin !== 1"
                             :music="{
                                      title: file.fileOriginName,
                                      artist: '',
                                      src: file.fileUrl,
                                      pic: ''
                                    }" />
                  </template>

                  <!-- office/其他附件 -->
                  <template v-for="(wendang, i3) in $fileSuffix.wendang"
                            :key="i3">
                    <chat-attachment v-if="wendang.fileSuffix === file.fileSuffix"
                                     :fileName="file.fileOriginName"
                                     :fileSize="'1kb'"
                                     :fileIcon="wendang.fileUrl"></chat-attachment>
                  </template>
                </div>

              </div>
              <!-- 弹框,自定义一个属性ITem -->
              <div class="more">
                <span class="icon-style">
                  <van-icon class="iconfont self-popover"
                            :data-msg-id='item.msgId'
                            class-prefix="icon-ali"
                            name="iconfontico"
                            color="#1296db" />
                </span>

                <div class="popover"
                     :class="item.popover.showPopover?'':'popover-dispaly'">
                  <div class="popover-item"
                       v-for="(popoverItem, index0) in item.popover.actions"
                       :key="index0">{{popoverItem.text}}</div>
                </div>
              </div>

            </div>
            <div class="read-style">未读</div>
          </div>
        </div>

        <!-- 我的 -->
        <div class="word-my"
             v-else>
          <div class="info">
            <p class="time">{{$filters.dataformat(Number(item.sendMsgTime), "YYYY-MM-DD HH:mm:ss")}} {{ item.nickName }}</p>

            <div class="content-more-style">

              <!-- 弹框 -->
              <div class="more">
                <span class="icon-style">
                  <van-icon class="iconfont self-popover"
                            :data-msg-id='item.msgId'
                            class-prefix="icon-ali"
                            name="iconfontico"
                            color="#1296db" />
                </span>
                <div class="popover"
                     :class="item.popover.showPopover?'':'popover-dispaly'">
                  <div class="popover-item"
                       v-for="(popoverItem, index0) in item.popover.actions"
                       :key="index0">{{popoverItem.text}}</div>
                </div>
              </div>

              <div class="info-content"
                   :style="item.chatContentType===0?myInfoContentText:myInfoContentFujian">
                <!-- 文本 -->
                <div v-if="item.chatContentType===0"
                     class="chat-margin"><span v-html="item.chatContent"></span></div>

                <div v-else-if="item.chatContentType===2"
                     v-for="(file,index1) in item.chatContent"
                     :key="index1">
                  <!-- 图片 -->
                  <template v-for="(tupian, i0) in $fileSuffix.tupian"
                            :key="i0">
                    <chat-image v-if="tupian === file.fileSuffix"
                                :imgSrc="file.fileUrl"></chat-image>
                  </template>

                  <!-- 视频 -->
                  <template v-for="(shipin, i1) in $fileSuffix.shipin"
                            :key="i1">
                    <video-player v-if="shipin.suffix === file.fileSuffix"
                                  class="vjs-custom-skin"
                                  ref="videoPlayer"
                                  :playsinline="true"
                                  :options="{...playerOptions, sources: [{type: shipin.mime, src: file.fileUrl }]}"></video-player>
                  </template>

                  <!-- 音频 -->
                  <template v-for="(yinpin, i2) in $fileSuffix.yinpin"
                            :key="i2">
                    <aplayer v-if="yinpin === file.fileSuffix && file.isYuyin !== 1"
                             :music="{
                                      title: file.fileOriginName,
                                      artist: '',
                                      src: file.fileUrl,
                                      pic: ''
                                    }" />
                  </template>

                  <!-- 语音 -->
                  <chat-yuyin v-if="file.fileSuffix === '.wav' && file.isYuyin === 1"
                              :yuyinSrc="file.fileUrl"
                              :fromMe="item.fromMe"></chat-yuyin>

                  <!-- office/其他附件 -->
                  <template v-for="(wendang, i3) in $fileSuffix.wendang"
                            :key="i3">
                    <chat-attachment v-if="wendang.fileSuffix === file.fileSuffix"
                                     :fileName="file.fileOriginName"
                                     :fileSize="'1kb'"
                                     :fileIcon="wendang.fileUrl"></chat-attachment>
                  </template>
                </div>

              </div>
            </div>
            <div class="read-style">已读</div>
          </div>

          <img :src="item.avatarUrl"
               @click="navigatorMy" />
        </div>
      </div>
    </div>
    <!-- </van-pull-refresh> -->

  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import chatImage from './ChatImage.vue';
import chatAttachment from './ChatAttachment.vue';
import chatYuyin from './ChatYuyin.vue';
// 引入自定义指令
export default {
  props: {
    chatRecords: {
      type: Array,
      default () {
        return []
      },
    },
    // 对方唯一标识
    toIdentity: {
      type: String,
      default () {
        return ''
      },
    }
  },
  //import引入的组件需要注入到对象中才能使用
  components: {
    chatImage,
    chatAttachment,
    chatYuyin
  },
  data () {
    //这里存放数据
    return {
      // 内容的样式
      myInfoContentText: { '--my-info-content-bgColor': 'rgb(158, 234, 106)', '--my-info-content-borderLeft': '0.26667rem solid rgb(158, 234, 106)' },
      myInfoContentFujian: { '--my-info-content-bgColor': 'none', '--my-info-content-borderLeft': 'none' },

      //默认15.35rem
      chatContentHeight: '15.35rem',
      ListenerOption: {
        // 是否存在打开的弹框，true-存在，false-不存在
        isActive: false,
        // 当前处在的激活的id
        currentActiveMsgId: '',
      },
      // 语音时长默认0
      // 聊天记录数据，按照发送时间排好序的数据
      recordContent: [
        {
          //消息id
          msgId: "1",
          //用户id
          userId: "1",
          //用户昵称
          nickName: "转功能三",
          //用户头像url
          avatarUrl: "https://img01.yzcdn.cn/vant/cat.jpeg",
          //聊天内容类型：文本，表情，语音，视频，图片，文件......
          chatContentType: "0",
          //聊天内容
          chatContent:
            "你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面你也很好，初次见面",
          //发送或接受时间
          sendMsgTime: "2021-08-19 16:44:32",
          //是否是我发送的
          fromMe: 1,

          //是否展示气泡
          popover: {
            showPopover: false,
            actions: [
              { text: "删除" },
              { text: "添加" },
            ],
          },
        },

      ],

      // 视频播放属性配置
      playerOptions: {
        //播放速度
        playbackRates: [0.5, 1.0, 1.5, 2.0],
        //如果true,浏览器准备好时开始回放。
        autoplay: false,
        // 默认情况下将会消除任何音频。
        muted: false,
        // 导致视频一结束就重新开始。
        loop: false,
        // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        preload: 'auto',
        language: 'zh-CN',
        // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        aspectRatio: '16:9',
        // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        fluid: true,
        sources: [{
          //默认类型类型，mp4
          type: "video/mp4",
          src: "",
          // type: "video/mp4",
          // src: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",
          // type: "application/x-mpegURL",
          // src: 'http://hls.cntv.lxdns.com/asp/hls/main/0303000a/3/default/978a64ddd3a1caa85ae70a23414e6540/main.m3u8',
        }],
        //你的封面地址，图片地址，可以获取视频帧作为图片地址
        poster: '',
        //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        notSupportedMessage: '此视频暂无法播放，请稍后再试',
        // 视频播放控制显示按钮
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true // 是否显示全屏按钮
        }
      },
    };
  },
  //方法集合
  methods: {
    // 跳转到对方的个人信息页面
    navigatorOthersInfo (userId) {
      this.$router.push({ name: "OthersInfo", params: { identity: userId } });
    },
    // 跳转到自己的个人信息页面
    navigatorMy () {

      this.$router.push({ name: "MyInfo", params: { fromIdentity: this.toIdentity } });
    },

    // 选择按钮
    selectAction (action, index) {
      console.log(action, index);
    },
    // 事件监听器,进行处理显示与隐藏
    eventCallback (e) {

      // 1 判断当前点击的dom 是否是更多
      // 2 判断当前是否有打开的更多弹框，如果没有则不作处理
      if (e.target.classList.contains('self-popover')) {
        console.log("击中")
        // 如果存在激活的，则取出激活的dom 进行关闭，并将当前的dom 设置为激活的状态
        if (this.ListenerOption.isActive) {
          var newActiveMsgId = '';
          for (var i = 0; i < this.chatRecords.length; i++) {
            var content = this.chatRecords[i];
            if (content.msgId === this.ListenerOption.currentActiveMsgId) {
              // 关闭之前的弹框
              this.chatRecords[i].popover.showPopover = false;
            }
            if (content.msgId === e.target.dataset.msgId) {
              // 选中的展示
              this.chatRecords[i].popover.showPopover = true;
              // 并将当前激活设置为选中的
              newActiveMsgId = content.msgId;
            }
          }
          this.ListenerOption.currentActiveMsgId = newActiveMsgId;
        } else {
          for (var i = 0; i < this.chatRecords.length; i++) {
            var content = this.chatRecords[i];
            // 将当前的dom 设置为激活的状态
            if (content.msgId === e.target.dataset.msgId) {
              // 选中的展示
              this.chatRecords[i].popover.showPopover = true;
              // 并将当前激活设置为选中的
              this.ListenerOption.currentActiveMsgId = content.msgId;
              this.ListenerOption.isActive = true;
              break;
            }
          }
        }

      } else {
        if (this.ListenerOption.isActive) {
          // 如果存在激活的，则关闭
          for (var i = 0; i < this.chatRecords.length; i++) {
            var content = this.chatRecords[i];
            if (content.msgId === this.ListenerOption.currentActiveMsgId) {
              // 关闭之前的弹框
              this.chatRecords[i].popover.showPopover = false;
              this.ListenerOption.currentActiveMsgId = '';
              this.ListenerOption.isActive = false;
              break;
            }
          }
        }
      }

    },

    // 监听改变聊天内容高度
    changeChatContentHeight (data) {
      this.chatContentHeight = data.chatHeight;
    },
  },

  //监听属性 类似于data概念
  computed: {
    // 是图片
    isTupian: function () {
      return this.message.split('').reverse().join('')
    }

  },
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // 监听聊天高度变化
    this.$emitter.on('changeChatContentHeight', this.changeChatContentHeight);
    // 监听
    document.addEventListener("click", this.eventCallback);
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () { },
  //生命周期 - 创建之前
  beforeCreate () { },
  //生命周期 - 挂载之前
  beforeMount () { },
  //生命周期 - 更新之前
  beforeUpdate () { },
  //生命周期 - 更新之后
  updated () { },
  //生命周期 - 销毁之前
  beforeUnmount () { },
  //生命周期 - 销毁完成
  unmounted () {
    this.$emitter.off('changeChatContentHeight', this.changeChatContentHeight);
    // 移除监听
    document.removeEventListener("click", this.eventCallback);
  },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated () { },

};
</script>
<style lang="less" scoped>
//@import url(); 引入公共css类

.chat-window-container {
  background-color: rgb(245, 245, 245);
}

.chat-content {
  padding: 0.48rem 0.32rem 0.48rem 0.32rem;
  //  max-height: 15.35rem;
  // height: 15.35rem;
  //height: 8rem;

  overflow-y: auto;

  .word {
    display: flex;
    margin-bottom: 20px;
    justify-content: flex-end;

    //margin-left: 30px;
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }
    .info {
      width: 90%;
      margin-left: 10px;
      .time {
        font-size: 12px;
        color: rgba(51, 51, 51, 0.8);
        margin: 0;
        height: 20px;
        line-height: 20px;
        margin-top: -5px;
        margin-bottom: 8px;
      }
      .read-style {
        color: #1296db;
      }
      .content-more-style {
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        align-items: center;
        .info-content {
          max-width: 235px;
          //padding: 8px;
          font-size: 14px;
          background-color: rgb(255, 255, 255);
          position: relative;
          float: left;
          .chat-margin {
            margin: 8px;
          }
        }
        .more {
          width: 20px;
          line-height: 36.5px;
          position: relative;
          .popover {
            display: flex;
            flex: 1;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            flex-wrap: nowrap;
            align-content: flex-start;
            align-items: center;
            color: #fff;
            font-size: 0.37333rem;
            z-index: 1;
            background-color: #4a4a4a;
            right: -0.82rem;
            width: 1.12rem;
            line-height: 1rem;
            text-align: center;
            position: absolute;
            cursor: pointer;
            overflow: visible;
            transition: opacity 0.15s, transform 0.15s;
            border-radius: 0.16rem;
            .popover-item {
              width: 80%;
              border-bottom: 0.02667rem solid #646566;
            }
          }
          .popover-dispaly {
            display: none;
          }
          //上小三角形
          .popover::after {
            position: absolute;
            right: 0.6rem;
            top: -0.4rem;
            content: "";
            border-width: 8px 8px 8px 8px;
            border-style: solid;
            border-color: transparent transparent #4a4a4a transparent;
          }
        }
      }

      //小三角形
      .info-content::before {
        position: absolute;
        left: -8px;
        top: 8px;
        content: "";
        border-right: 10px solid rgb(255, 255, 255);
        border-top: 8px solid transparent;
        border-bottom: 8px solid transparent;
      }
    }
  }

  .word-my {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
    //margin-right: 30px;

    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }
    .info {
      width: 90%;
      margin-left: 10px;
      text-align: right;
      .time {
        font-size: 12px;
        color: rgba(51, 51, 51, 0.8);
        margin: 0;
        height: 20px;
        line-height: 20px;
        margin-top: -5px;
        margin-right: 10px;
        margin-bottom: 8px;
      }
      .read-style {
        padding-right: 10px;
        color: #1296db;
      }
      .content-more-style {
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        align-items: center;
        justify-content: flex-end;
        .info-content {
          max-width: 235px;
          //padding: 8px;
          font-size: 14px;
          float: right;
          margin-right: 10px;
          position: relative;
          background-color: var(
            --my-info-content-bgColor
          ); //rgb(158, 234, 106);
          text-align: left;
          .chat-margin {
            margin: 8px;
          }
        }
        .more {
          width: 20px;
          line-height: 36.5px;
          position: relative;
          .popover {
            display: flex;
            flex: 1;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            flex-wrap: nowrap;
            align-content: flex-start;
            align-items: center;
            color: #fff;
            font-size: 0.37333rem;
            z-index: 1;
            background-color: #4a4a4a;
            width: 1.12rem;
            line-height: 1rem;
            right: 0.2rem;
            text-align: center;
            position: absolute;
            cursor: pointer;
            overflow: visible;
            transition: opacity 0.15s, transform 0.15s;
            border-radius: 0.16rem;
            .popover-item {
              width: 80%;
              border-bottom: 0.02667rem solid #646566;
            }
          }
          .popover-dispaly {
            display: none;
          }
          //上小三角形
          .popover::after {
            position: absolute;
            right: 0.15rem;
            top: -0.4rem;
            content: "";
            border-width: 8px 8px 8px 8px;
            border-style: solid;
            border-color: transparent transparent #4a4a4a transparent;
          }
        }
      }

      //小三角形
      .info-content::after {
        position: absolute;
        right: -8px;
        top: 8px;
        content: "";
        border-left: var(
          --my-info-content-borderLeft
        ); //10px solid rgb(158, 234, 106);
        border-top: 8px solid transparent;
        border-bottom: 8px solid transparent;
      }
    }
  }
}
// 音频播放器样式
.aplayer {
  overflow: visible;
}
</style>
